package com.tz.tzgw.pc.web.commondata;

import com.tz.tzgw.pc.web.dao.*;
import com.tz.tzgw.pc.web.model.Company;
import com.tz.tzgw.pc.web.model.Site;
import com.tz.tzgw.pc.web.model.Webcolumn;
import com.tz.tzgw.pc.web.model.ZtSet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Component
public class CommonDataInterceptor implements HandlerInterceptor {

    @Autowired
    private WebcolumnDao webcolumnDao;

    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private SiteDao siteDao;

    @Autowired
    private ZtSetDao ztSetDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String uri = request.getRequestURI();

        request.setAttribute("commonUri", uri);
        List<Webcolumn> columnlist = webcolumnDao.getAllParentColumn(0l);

        List<ZtSet> ztset = ztSetDao.getAllZtSets(1);

        if (ztset != null && !ztset.isEmpty()) {
            for (ZtSet zt : ztset) {
                zt.setUrl("video-2?setid="+zt.getId());
            }
        }

        List<Webcolumn> webcolumns = new ArrayList<>();

        if (ztset != null) {
            for (ZtSet zt : ztset) {
                try {
                    Webcolumn webcolumn = webcolumnDao.convertZtSetToWebcolumn(zt);
                    if (webcolumn != null) {
                        webcolumns.add(webcolumn);
                    }
                } catch (Exception e) {
                    e.printStackTrace(); // 处理转换异常，例如记录日志或显示错误消息。
                }
            }
        }


        columnlist.addAll(webcolumns);
        // 定义一个比较器，根据sort_order字段进行排序
        Comparator<Webcolumn> comparator = (c1, c2) -> {
            if (c1.getSort_order() != null && c2.getSort_order() != null) {
                return c2.getSort_order().compareTo(c1.getSort_order()); // 反转比较结果
            } else if (c1.getSort_order() != null) {
                return -1; // 如果c1有sort_order，而c2没有，返回负数，确保c1排在c2前面
            } else if (c2.getSort_order() != null) {
                return 1; // 如果c2有sort_order，而c1没有，返回正数，确保c2排在c1前面
            } else {
                return c2.getName().compareTo(c1.getName()); // 反转name字段的比较结果
            }
        };

        Collections.sort(columnlist, comparator);

        request.setAttribute("commonColumns", columnlist);


        Company company = companyDao.getInfo();
        request.setAttribute("commonCompany", company);

        Site site = siteDao.getInfo();
        request.setAttribute("commonSite", site);
        return true;
    }
}